<?php

namespace App\Http\Controllers\oem;

use App\Models\BankChargeLog;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OemController extends BaseController
{
    public function account()
    {
        $bank = Setting::get('bank');

        return $this->success($bank);
    }

    public function charge(Request $request)
    {
        $action = $request->input('action');
        $money = $request->input('money');

        if (!in_array($action, ['increase', 'decrease'])) {
            return $this->error("操作不合法");
        }

        DB::beginTransaction();
        try {
            $bank = Setting::get('bank');
            $beforeBalance = $bank['balance'];
            if ($action == 'increase') {
                $afterBalance = sprintf("%.2f", $beforeBalance + abs($money));
                $money = abs($money);
            } else {
                $afterBalance = sprintf("%.2f", $beforeBalance - abs($money));
                $money = -1 * abs($money);
            }

            Setting::set('bank', [
                'balance' => $afterBalance,
            ]);
            BankChargeLog::query()->create([
                'ip' => request()->ip(),
                'balance' => $money,
                'before_balance' => $beforeBalance,
                'after_balance' => $afterBalance,
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            $this->error($e->getMessage());
        }

        return $this->success(Setting::get('bank'));
    }

    public function history()
    {
        $list = BankChargeLog::query()->latest()->get();

        return $this->success($list);
    }

    public function lowest(Request $request)
    {
        $lowest = $request->input('lowest');

        Setting::set('bank', [
            'lowest_balance' => $lowest,
        ]);

        return $this->success(Setting::get('bank'));
    }
}
